package com.spzx.channel.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spzx.channel.service.IProductService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.product.api.domain.vo.ProductSkuVo;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.api.domain.vo.SpecValueVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Supplier;

/**
 * ClassName: ProductServiceImpl
 * Package: com.spzx.channel.service.impl
 * Description:
 */
@Service
@Slf4j
public class ProductServiceImpl implements IProductService {
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RedissonClient redissonClient;
    @Override
    public Map<String, Object> getSkuDetail(Long skuId) {
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
        if (!bloomFilter.contains(skuId)) {
            log.error("用户查询商品sku不存在：{}", skuId);
            //查询数据不存在直接返回空对象
            throw new ServiceException("用户查询商品sku不存在");
        }else {
            CountDownLatch latch = new CountDownLatch(6);
            Map<String, Object> map = new HashMap<>();

            CompletableFuture<Long> futureProductSku = CompletableFuture.supplyAsync(()-> {
                //获取sku
                R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
                if (R.FAIL == productSkuResult.getCode()) {
                    throw new ServiceException(productSkuResult.getMsg());
                }
                map.put("productSku", productSkuResult.getData());
                latch.countDown();
                return productSkuResult.getData().getProductId();

            }, threadPoolExecutor);

            futureProductSku.thenAcceptAsync(id -> {
                //获取商品信息
                R<Product> productResult = remoteProductService.getProduct(id .intValue(), SecurityConstants.INNER);
                if (R.FAIL==productResult.getCode()){
                    throw new ServiceException(productResult.getMsg());
                }
                //获取sliderUrlList
                List<String> sliderUrlList = Arrays.stream(productResult.getData().getSliderUrls().split(",")).toList();
                //获取specValueList
                List<SpecValueVo> specValueList = null;
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    String specValue = productResult.getData().getSpecValue();
                    specValueList = objectMapper.readValue(specValue, new TypeReference<List<SpecValueVo>>() {
                    });
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                map.put("product", productResult.getData());
                map.put("sliderUrlList", sliderUrlList);
                map.put("specValueList", specValueList);
                latch.countDown();
            });

            futureProductSku.thenAcceptAsync(id -> {
                //获取图片详情
                R<List<String>> productDetailsResult = remoteProductService.getProductDetails(id , SecurityConstants.INNER);
                if (R.FAIL==productDetailsResult.getCode()) {
                    throw new ServiceException(productDetailsResult.getMsg());
                }
                map.put("detailsImageUrlList", productDetailsResult.getData());
                latch.countDown();

            });

            futureProductSku.thenAcceptAsync(id -> {
                //获取skuValueMap
                R<Map<String, Long>> skuSpecValueResult = remoteProductService.getSkuSpecValue(id , SecurityConstants.INNER);
                if (R.FAIL==skuSpecValueResult.getCode()) {
                    throw new ServiceException(skuSpecValueResult.getMsg());
                }
                map.put("skuSpecValueMap", skuSpecValueResult.getData());
                latch.countDown();
            });


            CompletableFuture.runAsync(()->{
                //获取sku价格
                R<SkuPrice> skuPriceResult = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
                if (R.FAIL==skuPriceResult.getCode()) {
                    throw new ServiceException(skuPriceResult.getMsg());
                }
                map.put("skuPrice", skuPriceResult.getData());
                latch.countDown();
            });

            CompletableFuture.runAsync(()->{
                //获取库存信息
                R<SkuStockVo> skuStockResult = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
                if (R.FAIL==skuStockResult.getCode()) {
                    throw new ServiceException(skuStockResult.getMsg());
                }
                map.put("skuStockVo", skuStockResult.getData());
                latch.countDown();

            });
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return map;
        }
    }
}
